package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.publish;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.exception.AppException;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.DynamicPubParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.TopicResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.PostCardPickImageAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.GridSpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.FileUtil;
import com.kaiwukj.android.ufamily.utils.LocalMediaUtils;
import com.kaiwukj.android.ufamily.utils.VideoUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;


/**
 * Copyright © KaiWu Technology Company
 *
 * @author Haife
 * @job Android Development
 * @company KW | 开物科技
 * @time 2019/7/19
 * @desc 发布帖子
 */
public class DynamicPublishFragment extends BaseSwipeBackFragment<DynamicPublishPresenter> implements DynamicContract.PublishView {
    @BindView(R.id.rv_social_circle_card_imgs)
    RecyclerView mPostCardImageRv;
    //@BindView(R.id.rv_post_card_tags)
    //RecyclerView mCardTypeRv;
    @BindView(R.id.et_social_circle_card_content)
    EditText mContentEt;
    @BindView(R.id.tv_topic)
    TextView tvTopic;

    private List<LocalMedia> mediaPath;

    //@Inject
    //List<CircleCardResult> mCardResults;

    public static final String POST_CARD_TOPIC_FRAGMENT = "POST_CARD_TOPIC_FRAGMENT";
    //private List<LocalMedia> voucherImage = new ArrayList<>();
    private PostCardPickImageAdapter mPostCardAdapter;
    //选择图片的按钮
    //private LocalMedia pickItem;
    //发帖请求的实体类
    private DynamicPubParams requestParams = new DynamicPubParams();

    private TopicResult pickTopic;

    @OnClick(R.id.root_view)
    public void onRootViewClick() {
        mContentEt.requestFocus();
    }

    public static DynamicPublishFragment newInstance(List<LocalMedia> medias) {
        DynamicPublishFragment fragment = new DynamicPublishFragment();
        fragment.mediaPath = medias;
        return fragment;
    }

    @OnClick({R.id.iv_image, R.id.iv_video, R.id.iv_topic, R.id.container_topic})
    void onMediaClick(View view) {
        switch (view.getId()) {
            case R.id.iv_image:
                chooseMedia(0);
                break;
            case R.id.iv_video:
                chooseMedia(1);
                break;
            case R.id.container_topic:
            case R.id.iv_topic:
                ARouter.getInstance().build(ARouterUrlKt.TopicPickUrl)
                        .navigation(getActivity(), 1);
                break;
            default:
                break;
        }
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_circle_post_card_topic;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        if (getActivity() != null) {
            QMUITopBar topBar = this.getActivity().findViewById(R.id.qtb_social_circle);
            if (topBar != null)
                initTopBar(topBar);
        }

        mContentEt.setOnTouchListener((v, event) -> {
            // 解决scrollView中嵌套EditText导致不能上下滑动的问题
            v.getParent().requestDisallowInterceptTouchEvent(true);
            if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });
        initImageRV();

    }

    private void initImageRV() {
        mPostCardAdapter = new PostCardPickImageAdapter();
        @SuppressLint("InflateParams")
        QMUIRelativeLayout footerView = (QMUIRelativeLayout) LayoutInflater
                .from(getContext()).inflate(R.layout.item_widget_pic_select_footer,
                        null);

        footerView.setRadius(SizeUtils.dp2px(3));

        footerView.setOnClickListener(v -> showMediaDialog());

        mPostCardAdapter.setFooterViewAsFlow(true);
        mPostCardAdapter.addFooterView(footerView);
        mPostCardImageRv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mPostCardImageRv.addItemDecoration(new GridSpaceItemDecoration(5, 10));
        mPostCardImageRv.setAdapter(mPostCardAdapter);

        mPostCardAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_delete) {
                mPostCardAdapter.removeAt(position);
            }
        });

        mPostCardAdapter.registerAdapterDataObserver(mImageAdapterDataObserver);
    }

    private RecyclerView.AdapterDataObserver mImageAdapterDataObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            notifyAdapterStatus();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            super.onItemRangeChanged(positionStart, itemCount);
            notifyAdapterStatus();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            notifyAdapterStatus();
        }
    };

    private void notifyAdapterStatus() {
        if (mPostCardAdapter.getDataCount() > 0) {
            mPostCardImageRv.setVisibility(View.VISIBLE);
            ViewGroup footerView = mPostCardAdapter.getFooterLayout();
            if (footerView != null) {
                if (mPostCardAdapter.hasVideo() || mPostCardAdapter.getDataCount() == 9) {
                    footerView.setVisibility(View.GONE);
                } else {
                    footerView.setVisibility(View.VISIBLE);
                }
            }
        } else {
            mPostCardImageRv.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        assert mPresenter != null;
        // mPresenter.requestCircleCardList();
        // mContentEt.requestFocus();
        processClick();//发布

        if (mediaPath != null && mediaPath.size() > 0) {

            if (mediaPath.get(0).getMimeType().equals("video/mp4")) {
                LocalMediaUtils.handlePath(mediaPath);
                subscribe(Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    // LogUtils.d("size01---------------------->" + FileUtils.getSize(result.get(0).getRealPath()));
                    VideoUtils.getInstance().startCompressed(getContext(), mediaPath.get(0).getRealPath(), -1, new VideoUtils.OnVideoDealListener() {
                        @Override
                        public void onSuccess(String filePath) {
                            emitter.onNext(filePath);
                        }

                        @Override
                        public void onFailed(int errorCode, String errorMsg) {
                            // showMessage(errorCode + ":" + errorMsg);
                            emitter.onError(new AppException(errorCode, errorMsg));
                        }

                        @Override
                        public void onProgressUpdate(float progress) {
                        }
                    });
                })
                        .doOnSubscribe(act -> showLoading("正在处理..."))
                        .doFinally(this::hideLoading)
                        .subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result1 -> {
                            // LogUtils.d("size01---------------------->" + FileUtils.getSize(result1));
                            mediaPath.get(0).setRealPath(result1);
                            mPostCardAdapter.setList(mediaPath);

                        }, error -> {
                            if (error instanceof AppException) {
                                if (((AppException) error).getErrCode() == 8 || ((AppException) error).getErrCode() == 9) {
                                    mPostCardAdapter.setList(mediaPath);
                                    return;
                                }
                            }
                            showMessage(Objects.requireNonNull(error.getMessage()));
                        }));
            } else {
                mPostCardAdapter.setList(mediaPath);
            }


        }
    }


    private void processClick() {
        //选择类型发布类型
        mPostCardAdapter.setOnItemClickListener((adapter, view, position) -> {
            LocalMedia topItem = mPostCardAdapter.getItem(0);
            if (topItem == null) return;
            if (topItem.getMimeType().equals("video/mp4")) {
                PictureSelector.create(DynamicPublishFragment.this)
                        .externalPictureVideo(topItem.getPath());
            } else {
                List<LocalMedia> voucherImage2 = new ArrayList<>();
                for (int i = 0; i < mPostCardAdapter.getDataCount(); i++) {
                    if (i != mPostCardAdapter.getDataCount()) {
                        voucherImage2.add(mPostCardAdapter.getItem(i));
                    }
                }
                PictureSelector.create(DynamicPublishFragment.this)
                        .themeStyle(R.style.MyImagePickerStyle).openExternalPreview(position, voucherImage2);
            }
        });

    }

    private void initTopBar(QMUITopBar topBar) {
        topBar.addLeftBackImageButton().setOnClickListener(view -> killMyself());
        topBar.setTitle(getString(R.string.social_circle_post_topic));
        View containerRelease = View.inflate(getContext(), R.layout.weight_release_topbar_btn, null);
        View releaseBtn = containerRelease.findViewById(R.id.btn_release);
        RelativeLayout.LayoutParams layoutParams = topBar.generateTopBarTextButtonLayoutParams();
        topBar.addRightView(containerRelease, R.id.qmui_top_right_btn, layoutParams);

        //topBar.addRightImageButton(R.mipmap.icon_post_card_right_btn, R.id.qmui_top_right_btn)
        releaseBtn.setOnClickListener(view -> {
            String content = mContentEt.getText().toString();
            if (mPostCardAdapter.getDataCount() == 0 && StringUtils.isEmpty(content)) {
                showMessage(getString(R.string.post_card_input_content_hint));
                return;
            }
            requestParams.setDynamicContent(content);

            assert mPresenter != null;
            //图片地址
            List<String> paths = new ArrayList<>();
            //视频地址
            List<String> videoPath = new ArrayList<>();
            //voucherImage.remove(pickItem);
            if (mPostCardAdapter.getDataCount() > 0) {
                for (LocalMedia item : mPostCardAdapter.getData()) {
                    if (item.getMimeType().equals("video/mp4")) {
                        videoPath.add(item.getRealPath());
                        //发布视频
                        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                        //   mmr.setDataSource(getContext(), Uri.parse(item.getPath()));
                        mmr.setDataSource(item.getRealPath());
                        // mmr.setDataSource(new File(item.getPath()).getAbsolutePath());
                        // 通过视频路径获取bitmap
                        Bitmap bitmap = mmr.getFrameAtTime();
                        //把bitmap保存到sdcard然后得到图片的路径
                        String imagePath = FileUtil.saveBitmapToSDCard(bitmap, System.currentTimeMillis() + ".jpg");
                        requestParams.setImages(imagePath);
                    } else {
                        //发布图片
                        paths.add(item.getCompressPath());
                    }
                }
                if (videoPath.size() != 0) {
                    mPresenter.requestQIToken(requestParams, videoPath, true);
                } else {
                    mPresenter.requestQIToken(requestParams, paths, false);
                }

            } else {
                mPresenter.publishDynamic(requestParams);
            }

            view.setEnabled(false);
        });
    }

    private void showMediaDialog() {
        new QMUIBottomSheet.BottomListSheetBuilder(getContext())
                .addItem("图片")
                .addItem("视频")
                .setGravityCenter(true)
                .setOnSheetItemClickListener((dialog1, itemView, position12, tag) -> {
                    chooseMedia(position12);
                    dialog1.dismiss();
                }).build().show();
    }

    @SuppressLint("CheckResult")
    private void chooseMedia(int pos) {
        RxPermissions rxPermission = new RxPermissions(this);
        Disposable disposable = rxPermission.requestEach(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(permission -> {
            if (permission.granted) {
                if (pos == 0) {
                    if (mPostCardAdapter.isVideo()) {
                        showMessage("不能同时选择图片和视频");
                        return;
                    }
                    PictureSelector.create(DynamicPublishFragment.this)
                            .openGallery(PictureMimeType.ofImage())
                            // .selectionMode(PictureConfig.SINGLE)
                            .imageEngine(GlideEngine.createGlideEngine())
                            .isCompress(true)
                            .compressQuality(75)
                            .maxSelectNum(9 - mPostCardAdapter.getDataCount())
                            .minimumCompressSize(100)
                            .theme(R.style.MyImagePickerStyle)
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(List<LocalMedia> result) {
                                    //LocalMediaUtils.handlePath(result);
                                    mPostCardAdapter.addData(result);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                } else {
                    if (mPostCardAdapter.isImage()) {
                        showMessage("不能同时选择图片和视频");
                        return;
                    }
                    PictureSelector.create(DynamicPublishFragment.this)
                            .openGallery(PictureMimeType.ofVideo())
                            // .selectionMode(PictureConfig.SINGLE)
                            .imageEngine(GlideEngine.createGlideEngine())
                            .videoMaxSecond(15)
                            .videoMinSecond(3)
                            .maxSelectNum(1)
                            .maxVideoSelectNum(1)
                            .queryMaxFileSize(50)
                            .minimumCompressSize(100)
                            .theme(R.style.MyImagePickerStyle)
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(List<LocalMedia> result) {
                                    LocalMediaUtils.handlePath(result);
                                    // 选择本地视频压缩
                                    subscribe(Observable.create((ObservableOnSubscribe<String>) emitter -> {
                                        VideoUtils.getInstance().startCompressed(getContext(), result.get(0).getRealPath(), -1, new VideoUtils.OnVideoDealListener() {
                                            @Override
                                            public void onSuccess(String filePath) {
                                                emitter.onNext(filePath);
                                            }

                                            @Override
                                            public void onFailed(int errorCode, String errorMsg) {
                                                // showMessage(errorCode + ":" + errorMsg);
                                                emitter.onError(new AppException(errorCode, errorMsg));
                                            }

                                            @Override
                                            public void onProgressUpdate(float progress) {
                                            }
                                        });
                                    })
                                            .doOnSubscribe(act -> showLoading("正在处理..."))
                                            .doFinally(() -> hideLoading())
                                            .subscribeOn(Schedulers.computation())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(result1 -> {
                                                hideLoading();
                                                LocalMedia localMedia = result.get(0);
                                                // localMedia.setPath(result1);
                                                localMedia.setRealPath(result1);
                                                mPostCardAdapter.setList(result);
                                            }, error -> {
                                                if (error instanceof AppException) {
                                                    if (((AppException) error).getErrCode() == 8 || ((AppException) error).getErrCode() == 9) {//需要认证
                                                        mPostCardAdapter.setList(result);
                                                        return;
                                                    }
                                                }
                                                showMessage(Objects.requireNonNull(error.getMessage()));
                                                // showMessage(Objects.requireNonNull(error.getMessage()));

                                            }));
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                    hideLoading();
                }
                // .forResult(PictureConfig.CHOOSE_REQUEST);
            } else if (permission.shouldShowRequestPermissionRationale) {
                // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框

            } else {
                // 用户拒绝了该权限，并且选中『不再询问』

            }
        });

        subscribe(disposable);

    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mPostCardAdapter != null && mPostCardAdapter.hasObservers()) {
            mPostCardAdapter.unregisterAdapterDataObserver(mImageAdapterDataObserver);
        }
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == DynamicPublishPresenter.PUBLISH) {
            EventBus.getDefault().post(new HomeEvent(HomeEvent.DYNAMIC_PUBLISH));
            new Handler().postDelayed(() -> {
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }, 1500);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                pickTopic = (TopicResult) data.getExtras().getSerializable("topic");
                if (pickTopic != null) {
                    tvTopic.setText(pickTopic.getTopicTitle());
                    requestParams.setTopicId(pickTopic.getId());
                    requestParams.setTopicTitle(pickTopic.getTopicTitle());
                }
            }
        }
    }


}
